//
//  ZZEmoticonButtonView.swift
//  web
//
//  Created by 张卓 on 2017/2/10.
//  Copyright © 2017年 ZZ. All rights reserved.
//

import UIKit

enum  ZZEmoticonButtonViewType: Int{
    //最近
    case recent = 100
    //默认
    case normal = 101
    //emoji
    case emoji = 102
    //小浪花
    case xlh = 103
}

class ZZEmoticonButtonView: UIStackView {
    
    // 记录上一次选中的按钮
    var lastButton : UIButton?
    
    //1. 定义闭包
    var closure:((ZZEmoticonButtonViewType)->())?
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 提供一个方法共外界设置当前类里面的按钮状态
    func setupSelectButton(tag: Int){
        //通过tag获取button
        let button = viewWithTag(tag) as! UIButton
        if lastButton == button{
            return
        }
        button.isSelected = true
        lastButton?.isSelected = false
        lastButton = button
        
    }
    
    
    //MARK: - 监听事件
    func buttonClick(button:UIButton){
        if lastButton == button{
            return
        }
        button.isSelected = true
        lastButton?.isSelected = false
        lastButton = button
        
        // 执行闭包
        closure?(ZZEmoticonButtonViewType(rawValue:button.tag)!)
    }
    
    //MARK: - 设置视图
    private func setupUI(){
//        backgroundColor = ZZRandomColor()
        // 布局方式
        axis = .horizontal
        // 填充方式 
        distribution = .fillEqually
        addChildButtons(imgName: "left", title: "最近" ,type: .recent)
        addChildButtons(imgName: "mid", title: "默认" ,type: .normal)
        addChildButtons(imgName: "mid", title: "Emoji" ,type: .emoji)
        addChildButtons(imgName: "right", title: "小浪花" ,type: .xlh)
    }
    //创建按钮的公共方法
    func addChildButtons(imgName: String, title: String, type: ZZEmoticonButtonViewType){
        let button = UIButton()
        if title == "默认"{
            button.isSelected = true
         //记录
            lastButton = button
        }
        //设置tag
        button.tag = type.rawValue
        //监听事件
        button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
        button.setTitle(title, for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitleColor(UIColor.darkGray, for: UIControlState.highlighted)
        button.setBackgroundImage(UIImage(named:"compose_emotion_table_\(imgName)_normal"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named:"compose_emotion_table_\(imgName)_selected"), for: UIControlState.highlighted)
        addArrangedSubview(button)
        
    }
    

}
